//
//  DJDAudioTools.m
//  HCVideoModule
//
//  Created by 蒋千秋 on 2021/9/23.
//

#import "DJDAudioTools.h"
#import <AudioToolbox/AudioToolbox.h>
@interface DJDAudioTools()
@property (nonatomic,assign)SystemSoundID soundID;
@property (nonatomic,assign)BOOL stop;
@end
static DJDAudioTools *instance;
@implementation DJDAudioTools
+ (instancetype)share{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = DJDAudioTools.new;
        instance.soundID = 0;
    });
    return  instance;
}
- (void)playCallAudioForever:(BOOL)forever{
    self.stop = NO;
    NSString *audioFile=[[NSBundle mainBundle] pathForResource:@"call" ofType:@"caf"];
    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
    //1.获得系统声音ID
    /**
     * inFileUrl: 音频文件url
     * outSystemSoundID:声 id(此函数会将音效文件加入到系统音频服务中并返回一个长整形ID) */
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &_soundID);
    //如果需要在播放完之后执行某些操作,可以调用如下方法注册一个播放完成回调函数 AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
    //2.播放音频
   AudioServicesPlaySystemSound(self.soundID);//播放音效
    __weak typeof(self) weakSelf = self;
   AudioServicesPlaySystemSoundWithCompletion(self.soundID,^(void){
       AudioServicesRemoveSystemSoundCompletion(weakSelf.soundID);
       // 释放 systemSoundID
       AudioServicesDisposeSystemSoundID(weakSelf.soundID);
       if (forever && !weakSelf.stop) {
           [self playCallAudioForever:forever];
       }
  });

}
- (void)stopCallAudio{
        if (self.stop) return;
        self.stop = YES;
        //注销声音播放完成时间回调函数
        AudioServicesRemoveSystemSoundCompletion(self.soundID);
        // 释放 systemSoundID
        AudioServicesDisposeSystemSoundID(self.soundID);
}
@end
